from __future__ import with_statement

import sys
import time
from wsgiref.simple_server import make_server
from threading import Thread, Event
from kineta import *


class TestServer(Thread):

    def __init__(self):
        Thread.__init__(self)
        self.app = Server({'db': FileDB('db')})
        self._quitev = Event()
        self.setDaemon(True)
        self.start()
        time.sleep(.2) # give server a chance to get started :/

    def quit(self):
        self._quitev.set()

    def run(self):
        sys.stderr = FakeStdErr()
        serv = make_server('localhost', 20000, self.app)
        while not self._quitev.isSet():
            serv.handle_request()
        self.app.close()


class FakeStdErr(object):

    def write(self, val):
        pass
